<template>
  <div class="scenic-order-management">
    <div class="header">
      <h2>景点订单管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="16">
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-label">总订单数</div>
            <div class="stat-number">{{ totalOrders }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-label">景点数量</div>
            <div class="stat-number">{{ scenicData.length }}</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 景点折叠面板 -->
    <div class="scenic-collapse-container" v-loading="loading">
      <el-collapse v-model="activeScenics" accordion>
        <el-collapse-item
          v-for="scenic in scenicData"
          :key="scenic.scenicSpot.id"
          :title="`${scenic.scenicSpot.name} (${scenic.orderInfo.length}个订单)`"
        >
          <template #title>
            <div class="scenic-header">
              <span class="scenic-name">{{ scenic.scenicSpot.name }}</span>
              <el-tag type="info" size="small"
                >{{ scenic.orderInfo.length }}个订单</el-tag
              >
            </div>
          </template>

          <!-- 景点下的订单列表 -->
          <el-table
            :data="scenic.orderInfo"
            style="width: 100%"
            :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
          >
            <el-table-column prop="id" label="订单ID" width="80" />
            <!-- 替换用户ID列为用户名和头像 -->
            <el-table-column label="用户名" width="180">
              <template #default="scope">
                <div style="display: flex; align-items: center; gap: 8px">
                  <span
                    style="cursor: pointer; color: #409eff"
                    @click="handleViewDetail(scope.row)"
                  >
                    {{
                      userDetailsMap[scope.row.userId]?.username ||
                      scope.row.userId ||
                      "用户名称"
                    }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="visitDate" label="预约日期" width="120" />
            <el-table-column prop="totalAmount" label="总金额" width="100">
              <template #default="scope">
                {{ scope.row.totalAmount || "-" }}元
              </template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="订单状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.orderStatus)">
                  {{ getStatusText(scope.row.orderStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.updateTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleViewDetail(scope.row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :top="'3%'"
    >
      <template v-if="currentOrder">
        <!-- 订单基本信息 -->
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单ID">{{
            currentOrder.id
          }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusTagType(currentOrder.orderStatus)">
              {{ getStatusText(currentOrder.orderStatus) }}
            </el-tag>
          </el-descriptions-item>
          <template v-if="currentUserDetails">
            <el-descriptions-item label="用户名">{{
              currentUserDetails.username || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{
              currentUserDetails.phone || "-"
            }}</el-descriptions-item>
          </template>
          <template v-else>
            <el-descriptions-item label="用户信息">
              <el-tag type="info">正在查询用户信息...</el-tag>
            </el-descriptions-item>
          </template>
          <el-descriptions-item label="景点ID">{{
            currentOrder.scenicId
          }}</el-descriptions-item>
          <el-descriptions-item label="预约日期">{{
            currentOrder.visitDate
          }}</el-descriptions-item>
          <el-descriptions-item label="总金额"
            >{{ currentOrder.totalAmount || "-" }}元</el-descriptions-item
          >
          <el-descriptions-item label="创建时间">{{
            formatDate(currentOrder.createTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{
            formatDate(currentOrder.updateTime)
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 主联系人信息 -->
        <div style="margin-top: 20px">
          <h3 style="margin-bottom: 10px">主联系人信息</h3>
          <template v-if="touristsData.length > 0">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="姓名">{{
                touristsData.find((t) => t.isPrimary === "是")?.realName || "-"
              }}</el-descriptions-item>
              <el-descriptions-item label="手机号码">{{
                touristsData.find((t) => t.isPrimary === "是")?.phone || "-"
              }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{
                touristsData.find((t) => t.isPrimary === "是")?.idCard || "-"
              }}</el-descriptions-item>
              <el-descriptions-item label="票价"
                >{{
                  touristsData.find((t) => t.isPrimary === "是")?.ticketPrice ||
                  "-"
                }}元</el-descriptions-item
              >
            </el-descriptions>
          </template>
          <template v-else>
            <el-empty description="暂无主联系人信息" />
          </template>
        </div>

        <!-- 游客信息列表 -->
        <div style="margin-top: 20px">
          <h3 style="margin-bottom: 10px">游客信息</h3>
          <template
            v-if="touristsData.filter((t) => t.isPrimary === '否').length > 0"
          >
            <el-table
              :data="touristsData.filter((t) => t.isPrimary === '否')"
              style="width: 100%"
              size="small"
            >
              <el-table-column prop="realName" label="姓名" width="120" />
              <el-table-column prop="phone" label="手机号码" width="150" />
              <el-table-column prop="idCard" label="身份证号" width="200" />
              <el-table-column prop="ticketPrice" label="票价" width="80">
                <template #default="scope">
                  {{ scope.row.ticketPrice || "-" }}元
                </template>
              </el-table-column>
            </el-table>
          </template>
          <template v-else>
            <el-empty description="暂无游客信息" />
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import { Refresh, User } from "@element-plus/icons-vue";
import request from "@/utils/request";
import { getUserDetails } from "@/api/user";

// 响应式数据
const loading = ref(false);
const scenicData = ref([]);
const activeScenics = ref([]);
const detailDialogVisible = ref(false);
const currentOrder = ref(null);
const currentUserDetails = ref(null);
const touristsData = ref([]); // 存储游客信息
// 存储用户详情映射，用于表格中显示
const userDetailsMap = reactive({});

// 计算总订单数
const totalOrders = computed(() => {
  return scenicData.value.reduce((total, scenic) => {
    return total + scenic.orderInfo.length;
  }, 0);
});

// 异步加载用户详情，但不阻塞列表渲染
const loadUserDetails = async (userId) => {
  try {
    // 避免重复请求
    if (userDetailsMap[userId]) {
      return;
    }

    const userDetails = await getUserDetails(userId);
    if (userDetails) {
      userDetailsMap[userId] = userDetails;
    }
  } catch (error) {
    console.error(`获取用户ID ${userId} 详情失败:`, error);
    // 失败时不影响列表显示
  }
};

// 批量为订单加载用户详情
const loadUsersForOrders = async () => {
  const allOrders = scenicData.value.flatMap(
    (scenic) => scenic.orderInfo || []
  );
  const userIds = [
    ...new Set(allOrders.map((order) => order.userId).filter((id) => id)),
  ];

  // 异步请求用户详情，不阻塞UI
  userIds.forEach((userId) => {
    loadUserDetails(userId);
  });
};

// 方法 - 从API获取数据
const fetchScenicOrders = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      // 根据API要求添加必要参数，这里使用分页参数作为示例
      pageNum: 1,
      pageSize: 10,
    };

    // 使用项目封装的request工具发送请求，request.js中已配置baseURL
    const response = await request.post(
      "/admin/scenicOrder/getOrdersByScenicName",
      params
    );

    // request工具已在拦截器中直接返回data对象
    if (response && response.code === 200) {
      scenicData.value = response.data;
      ElMessage.success("数据加载成功");

      // 数据加载完成后，异步加载用户详情（不阻塞UI）
      loadUsersForOrders();
    } else {
      ElMessage.error("数据格式错误");
    }
  } catch (error) {
    ElMessage.error("数据加载失败，请重试");
    console.error("Failed to fetch scenic orders:", error);
  } finally {
    loading.value = false;
  }
};

// 方法 - 刷新数据
const handleRefresh = () => {
  fetchScenicOrders();
};

// 方法 - 查看订单详情
const handleViewDetail = async (order) => {
  currentOrder.value = order;
  currentUserDetails.value = null;
  touristsData.value = [];
  detailDialogVisible.value = true;

  try {
    // 通过订单中的userId查询用户详情
    const userDetails = await getUserDetails(order.userId);
    currentUserDetails.value = userDetails;

    // 获取订单的游客信息
    const touristsResponse = await request.post("/admin/orderTourist/page", {
      orderId: order.id,
      pageNum: 1,
      pageSize: 100, // 获取所有游客信息
    });

    if (
      touristsResponse &&
      touristsResponse.code === 200 &&
      touristsResponse.data
    ) {
      touristsData.value = touristsResponse.data.records || [];
    }
  } catch (error) {
    console.error("获取用户和游客详情失败:", error);
    ElMessage.warning("获取详情失败");
  }
};

// 方法 - 状态文本转换（处理数字类型的orderStatus）
const getStatusText = (status) => {
  const statusMap = {
    0: "待确认",
    1: "已确认",
    // 可以根据实际API返回值增加更多状态
  };
  return statusMap[status] || "未知状态";
};

// 方法 - 状态标签类型转换
const getStatusTagType = (status) => {
  const typeMap = {
    0: "warning", // 待确认
    1: "success", // 已确认
    // 可以根据实际API返回值增加更多状态类型
  };
  return typeMap[status] || "info";
};

// 方法 - 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return "-";
  return new Date(dateString).toLocaleString("zh-CN");
};

// 生命周期 - 组件挂载时获取数据
onMounted(() => {
  fetchScenicOrders();
});
</script>

<style scoped>
.scenic-order-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-left: auto;
  gap: 12px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  text-align: center;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-number {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.scenic-collapse-container {
  margin-bottom: 20px;
}

.scenic-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 20px;
}

.scenic-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .statistics .el-row {
    flex-direction: column;
  }

  .statistics .el-col {
    width: 100%;
    margin-bottom: 16px;
  }
}
</style>
